package com.aabte.nettyleran.netty.udp;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

/**
 * @author Daniel
 * @version 1.0
 * @date 2020/3/15
 */
public class ChineseProverbClient {

    public static void main(String[] args) throws InterruptedException {
        int port = 8080;
        if (args != null && args.length > 0) {
            try {
                Integer.valueOf(args[0]);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }

        // new ChineseProverbClient().run("255.255.255.255", port);
        new ChineseProverbClient().run("127.0.0.1", port);
    }

    private void run(String destHost, int destPort) throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group).channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true)
                .handler(new ChineseProverbClientHandler());

        try {
            Channel channel = bootstrap.bind(0).sync().channel();

            // 向对方机器发送UDP消息
            ByteBuf byteBuf = Unpooled.copiedBuffer("谚语字典查询?", StandardCharsets.UTF_8);
            channel.writeAndFlush(new DatagramPacket(byteBuf, new InetSocketAddress(destHost, destPort))).sync();

            if (!channel.closeFuture().await(15000)) {
                System.out.println("查询超时！");
            }
        } finally {
            group.shutdownGracefully();
        }

    }

    private static class ChineseProverbClientHandler extends SimpleChannelInboundHandler<DatagramPacket> {
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause.printStackTrace();
            ctx.close();
        }

        @Override
        protected void messageReceived(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
            String response = packet.content().toString(StandardCharsets.UTF_8);
            if (response.startsWith("谚语查询结果：")) {
                System.out.println(response);
                ctx.close();
            }
        }
    }
}
